<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">双选系统</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-link type="primary" style="float: right;" @click="losePasswordVisible = true">忘记密码</el-link>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
<!--      <span>Copyright © 2018-2021 ruoyi.vip All Rights Reserved.</span>-->
    </div>

    <el-dialog title="忘记密码" @close="cancel" :visible.sync="losePasswordVisible" width="480px" append-to-body>
      <el-form ref="updatePasswordForm" :model="updatePasswordForm" :rules="updatePasswordFormRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号" prop="username">
              <el-input v-model="updatePasswordForm.username" placeholder="请输入要修改密码的账号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="验证码" prop="checkCode">
              <el-input v-model="updatePasswordForm.checkCode" placeholder="请输入验证码" style="width: 70%" />
              <el-button v-show="passwordCheckCode.show" :disabled="updatePasswordForm.username==null" style="float: right" type="text" @click="getPasswordCheckCode">发送验证码</el-button>
              <span v-show="!passwordCheckCode.show" style="float: right;color: #409EFF;font-size: 18px;">{{passwordCheckCode.count}} s</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="新密码" prop="newPassword">
              <el-input type="password" v-model="updatePasswordForm.newPassword" placeholder="请输入新密码" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import { getUserByUsername,updatePassword ,sendResetMail} from "@/api/system/user";

import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      loading: false,
      redirect: undefined,
      losePasswordVisible:false,
      updatePasswordForm:{
        username:undefined,
        email:undefined,
        userId:undefined,
        newPassword:undefined
      },
      updatePasswordFormRules:{
        checkCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "change" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "change" }
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        username:[
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ]
      },
      passwordCheckCode:{
        show: true,
        count: '',
        timer: null,
      }
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            this.getCode();
          });
        }
      });
    },
    cancel(){
      this.losePasswordVisible = false
      this.$refs['updatePasswordForm'].resetFields()
    },
    async submitForm() {
      //修改密码
      console.log(this.updatePasswordForm)
      const res = await updatePassword(this.updatePasswordForm)
      // console.log(res)
      this.$message.success("修改成功")
      this.losePasswordVisible = false;
      this.$refs['updatePasswordForm'].resetFields()
    },
    async getPasswordCheckCode() {

      //获取用户信息
      const res = await getUserByUsername(this.updatePasswordForm.username)
      if (res.data.email==null||res.data.email==''){
        return this.$message.error("用户邮箱为空，请联系管理员")
      }
      this.updatePasswordForm.userId = res.data.userId
      this.updatePasswordForm.email = res.data.email
      //发送验证邮箱

      const resp = await sendResetMail(res.data.email)

      // console.log(resp)
      this.$message.success(`验证码已发送到邮箱${res.data.email}，请注意查收`)


      //倒计时
      const TIME_COUNT = 300;
      if (!this.timer) {
        this.passwordCheckCode.count = TIME_COUNT;
        this.passwordCheckCode.show = false;
        this.passwordCheckCode.timer = setInterval(() => {
          if (this.passwordCheckCode.count > 0 && this.passwordCheckCode.count <= TIME_COUNT) {
            this.passwordCheckCode.count--;
          } else {
            this.passwordCheckCode.show = true;
            clearInterval(this.timer);
            this.passwordCheckCode.timer = null;
          }
        }, 1000)
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
